package com.example.myremotecontroller;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;
import android.widget.*;

import com.inuker.bluetooth.library.utils.BluetoothLog;
import com.inuker.bluetooth.library.utils.ByteUtils;

import io.github.controlwear.virtual.joystick.android.JoystickView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private CarBLE ble_;

    private Button btnForward_;
    private Button btnBackward_;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        btnForward_ = (Button)findViewById(R.id.button_forward);
//        btnBackward_ = (Button)findViewById(R.id.button_backward);
//
//        btnForward_.setOnClickListener(this);
//        btnBackward_.setOnClickListener(this);

        JoystickView joystick = (JoystickView) findViewById(R.id.joystickView);
        joystick.setOnMoveListener(new JoystickView.OnMoveListener() {
            @Override
            public void onMove(int angle, int strength) {
                // do whatever you want
                // BluetoothLog.v(String.format("angle=%d, strenght=%d", angle, strength));
                int v=0, a=0;
                int ngt = 1;
                if(angle < 180) {
                    ngt = 1;
                }else{
                    ngt = -1;
                }
                v = (int) Math.round(ngt * 0x7FFF * strength / 100.0);

                if(strength == 0 /* && angle == 0 */) {
                    a = 0;
                } else if(angle >= 0 && angle < 90){
                    a = (int) Math.round(-32767 * (90 - angle) / 90.0);
                } else if (angle >= 90 && angle < 180) {
                    a = (int) Math.round(32767 * (angle - 90)/90.0);
                } else if(angle >= 180 && angle < 270) {
                    a = (int) Math.round(32767 * (270 - angle)/90.0);
                } else if(angle >= 270){
                    a = (int) Math.round(-32767 * (angle - 270)/90.0);
                }
                ble_.sendMoveCmd(v, a);
            }
        }, 200);

        ble_ = new CarBLE(getApplicationContext());
        ble_.connectTarget();
    }


    @Override
    public void onClick(View v) {
//        switch (v.getId()){
//            case R.id.button_forward:
//                ble_.sendBytes(ByteUtils.stringToBytes("a506017fff0000a9"));
//                break;
//            case R.id.button_backward:
//                ble_.sendBytes(ByteUtils.stringToBytes("a506010000000062"));
//                break;
//        }
    }
}
